﻿using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Unread.Business.Data.Opml.Interfaces;
using Unread.Business.Data.Opml.Model;
using Unread.Business.Data.Storage.Interfaces;
using Unread.Business.Models;
using Unread.Business.Repositories.Interfaces;
using Unread.Business.Services.Interfaces;
using Windows.Storage;
using Windows.Storage.Pickers;

namespace Unread.Business.Services
{
    [Export(typeof(IFeedsExporter))]
    internal class FeedsExporter : IFeedsExporter
    {
        private readonly List<KeyValuePair<string, IList<string>>> _fileTypes = new List<KeyValuePair<string, IList<string>>> 
        { 
            new KeyValuePair<string, IList<string>>("OPML", new List<string> { ".xml", ".opml" }) 
        };

        private readonly IFileWriterPicker _fileWriterPicker;
        private readonly IFeedRepository _feedRepository;
        private readonly IOpmlWriter _opmlWriter;

        [ImportingConstructor]
        public FeedsExporter(IFileWriterPicker fileWriterPicker, IFeedRepository feedRepository, IOpmlWriter opmlWriter)
        {
            if (fileWriterPicker == null) throw new ArgumentNullException("fileWriterPicker");
            if (feedRepository == null) throw new ArgumentNullException("feedRepository");
            if (opmlWriter == null) throw new ArgumentNullException("opmlWriter");

            _fileWriterPicker = fileWriterPicker;
            _feedRepository = feedRepository;
            _opmlWriter = opmlWriter;
        }

        public async Task Export()
        {
            var file = await _fileWriterPicker.PickSaveFileAsync(PickerLocationId.DocumentsLibrary, "unread", _fileTypes);
            if (file == null)
            {
                Debug.WriteLine("No feeds exported, no file selected");
                return;
            }

            var opmlAsString = await GetFeedsAsOpmlString();

            await FileIO.WriteTextAsync(file, opmlAsString);
        }

        private async Task<string> GetFeedsAsOpmlString()
        {
            var feeds = await _feedRepository.GetAll();

            var outlines = Feed.MapFeedsToOutlines(feeds.ToList());
            var opml = new Root
            {
                Head = new Head { Title = "Unread" },
                Body = new Body
                {
                    Outlines = outlines
                }
            };

            var opmlAsString = _opmlWriter.Write(opml);

            return opmlAsString;
        }
    }
}
